package com.steak.concurrent.CompletableFuture.api.allOf;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * @author 刘牌
 * @date 2022/3/2714:11
 */
public class AllOfTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<String> task1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("开始执行有返回值的异步任务 task1");
            return "task1";
        });
        CompletableFuture<String> task2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("开始执行有返回值的异步任务 task2");
            return "task2";
        });
        CompletableFuture<String> task3 = CompletableFuture.supplyAsync(() -> {
            System.out.println("开始执行有返回值的异步任务 task3");
            int i = 1 / 0;
            return "task3";
        });
        CompletableFuture<String> future = CompletableFuture.allOf(task1, task2, task3)
                .thenApplyAsync(s -> {
                    String res = "";
                    try {
                        res = task1.get() + task2.get() + task3.get();
                    } catch (InterruptedException | ExecutionException e) {
                        e.printStackTrace();
                    }
                    return res;
                });
        System.out.println("future  " + future.get());
    }
}
